package com.petalsgroup.petals.web.servlet.user;

import com.petalsgroup.petals.pojo.ResultInfo;
import com.petalsgroup.petals.pojo.UserDO;
import com.petalsgroup.petals.service.user.UserService;
import com.petalsgroup.petals.service.user.impl.UserServiceImpl;
import com.petalsgroup.petals.util.Md5Util;
import com.petalsgroup.petals.web.BaseServlet;
import org.apache.commons.beanutils.BeanUtils;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;
import java.util.Random;
//zzw
@WebServlet("/user/*")
public class UserLoginServlet extends BaseServlet {
    private UserService us = new UserServiceImpl();

    //进入登录界面
    public void toLogin(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setAttribute("login",true);
        req.getRequestDispatcher("/WEB-INF/user_view/login.jsp").forward(req,resp);
    }

    //进入注册界面
    public void toRegister(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setAttribute("login",false);
        req.getRequestDispatcher("/WEB-INF/user_view/login.jsp").forward(req,resp);
    }
    //登陆方法
    public void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //从前端获取数据
        String username = req.getParameter("username");
        String pass = req.getParameter("password");
        //密码加密
        String password = Md5Util.convertMD5(pass);
        String check = req.getParameter("check");

        //从session中获取验证码
        HttpSession session = req.getSession();
        String checkcode_server = (String) session.getAttribute("CHECKCODE_SERVER");
        //为了保证验证码只能使用一次
        session.removeAttribute("CHECKCODE_SERVER");

        UserDO user = new UserDO();
        user.setUsername(username);
        user.setPassword(password);

        //创建封装后端返回前端数据对象
        ResultInfo resultInfo = new ResultInfo();
        //判断验证码
        if(checkcode_server == null || !checkcode_server.equalsIgnoreCase(check)){
            //验证码错误

            //注册失败
            resultInfo.setFlag(false);
            resultInfo.setErrorMsg("验证码错误");

        }else {
            //调用service 的登录方法
            UserDO loginUser = us.login(user);
            if (loginUser!=null){
                //解密 存入session
                //loginUser.setPassword(Md5Util.convertMD5(user.getPassword()));
                req.getSession().setAttribute("user",loginUser);
                //登陆成功
                resultInfo.setFlag(true);
            }else {
                //登陆失败
                resultInfo.setFlag(false);
                resultInfo.setErrorMsg("用户名或密码错误");
            }
        }
        writeValue(resp,resultInfo);
    }

    public void checkCode(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //服务器通知浏览器不要缓存
        response.setHeader("pragma","no-cache");
        response.setHeader("cache-control","no-cache");
        response.setHeader("expires","0");

        //在内存中创建一个长80，宽30的图片，默认黑色背景
        //参数一：长
        //参数二：宽
        //参数三：颜色
        int width = 80;
        int height = 30;
        BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);

        //获取画笔
        Graphics g = image.getGraphics();
        //设置画笔颜色为灰色
        g.setColor(Color.GRAY);
        //填充图片
        g.fillRect(0,0, width,height);

        //产生4个随机验证码，12Ey
        String checkCode = getCheckCode();
        //将验证码放入HttpSession中
        request.getSession().setAttribute("CHECKCODE_SERVER",checkCode);

        //设置画笔颜色为黄色
        g.setColor(Color.YELLOW);
        //设置字体的小大
        g.setFont(new Font("黑体",Font.BOLD,24));
        //向图片上写入验证码
        g.drawString(checkCode,15,25);

        //将内存中的图片输出到浏览器
        //参数一：图片对象
        //参数二：图片的格式，如PNG,JPG,GIF
        //参数三：图片输出到哪里去
        ImageIO.write(image,"PNG",response.getOutputStream());
    }
    /**
     * 产生4位随机字符串
     */
    private String getCheckCode() {
        String base = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
        int size = base.length();
        Random r = new Random();
        StringBuffer sb = new StringBuffer();
        for(int i=1;i<=4;i++){
            //产生0到size-1的随机值
            int index = r.nextInt(size);
            //在base字符串中获取下标为index的字符
            char c = base.charAt(index);
            //将c放入到StringBuffer中去
            sb.append(c);
        }
        return sb.toString();
    }

    //注册
    public void register(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Map<String, String[]> map = req.getParameterMap();
        UserDO user = new UserDO();


        try {
            BeanUtils.populate(user,map);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        //创建封装后端返回前端数据对象
        ResultInfo resultInfo = new ResultInfo();
        //密码加密
        String pass = user.getPassword();
        String password = Md5Util.convertMD5(pass);
        user.setPassword(password);

        //调用service方法注册
        boolean b = us.regist(user);

        if (b){
            //注册成功
            resultInfo.setFlag(true);
        }else {
            //注册失败
            resultInfo.setFlag(false);
            resultInfo.setErrorMsg("注册失败");
        }

        /*传入的对象序列化为json，并且写回前端*/
        writeValue(resp,resultInfo);

    }


    //uuid
    public void uuid(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String code = request.getParameter("code");

        us.updateUuid(code);

        //request.getRequestDispatcher("").forward(request,response);
        response.sendRedirect(request.getContextPath()+"/user/toLogin");
    }

    //注册成功
    public void registerOK(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.getRequestDispatcher("/WEB-INF/user_view/register.jsp").forward(request,response);
    }

    //退出
    public void exit(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //移除session中的user
        request.getSession().invalidate();
        //跳转到login界面
        response.sendRedirect(request.getContextPath()+"/user/toLogin");
    }

    //跳转到找回密码界面
    public void findUser(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        request.getRequestDispatcher("/WEB-INF/user_view/findPassword.jsp").forward(request,response);
    }

    //找回密码
    public void findPassword(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String email = req.getParameter("email");
        UserDO user = new UserDO();
        user.setUsername(username);
        user.setEmail(email);

        //创建封装后端返回前端数据对象
        ResultInfo resultInfo = new ResultInfo();

        //调用service的方法
        Boolean b = us.findPassword(user);
        if (b){
            //已找回密码
            resultInfo.setFlag(true);
            resultInfo.setErrorMsg("已找回密码，通过邮箱查询");
        }else {
            //没有找到密码
            resultInfo.setFlag(false);
            resultInfo.setErrorMsg("账号或邮箱不正确");
        }

        /*传入的对象序列化为json，并且写回前端*/
        writeValue(resp,resultInfo);
    }
}
